<?php
//пароль
if (!defined('INCONFIG')) {
    Header("Location: ../index.php");
    die();
}
#Temp fix
function val_string($string)
{
    global $sql;
    if(!is_array($string))
        $string = trim(htmlentities(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $sql->escape($string)), ENT_QUOTES, 'UTF-8'));
    else
    {
        $strings = array();
        foreach($string as $key => $value)
        {
            array_push($strings,val_string($value));
        }
        $string=$strings;
    }
    return $string;
}

class user
{
    private $access=array();   
	function __construct()
	{
		if (isset($_SESSION['logged'])&& $_SESSION['logged'] && isset($_SESSION['user'])&& $_SESSION['user']!='')
		{
			$this->checkSession();
		} elseif (isset($_COOKIE['logincookie']))
		{
            $this->checkRemembered($_COOKIE['logincookie']);
		}
	}

	public function checkLogin( $username, $password, $remember )
	{
        global $sql;
		$user = $sql->escape($username);
		$pass = $this->encpass($password);
		$sqlq = "SELECT * FROM `employees` WHERE `user` = '$user' AND `pass` = '$pass'";
		$result = $sql->query($sqlq);

		if ($sql->num_rows())
		{
			$this->setSession($sql->fetch_array($result), $remember);
			return true;
		}
		else
		{
			return false;
		}
	}

	private function setSession($values, $remember, $init = true)
	{
        global $sql;
		$_SESSION['user'] = strtolower($values['user']);
        $cookie = $this->encpass($values['user'].$values['pass']);
        foreach($values as $key=>$value)
        {
            $_SESSION[$key]=$value;
        }
        //$_SESSION['cookie'] = $cookie;
		$_SESSION['logged'] = true;
        //$_SESSION['skin'] = $values['skin'];
        //$_SESSION['lang'] = $values['lang'];
		if ($remember){
			$this->updateCookie($cookie, true);
		}
		if ($init){
			$session = $sql->escape(session_id());
			$ip = $sql->escape($_SERVER['REMOTE_ADDR']);
			$sql->query("UPDATE `employees` SET `cookie` = '$cookie', `session` = '$session', `ip` = '$ip' WHERE `user` = '{$values[user]}'");
		}
        $qry_data=$sql->query("SELECT * FROM groups WHERE id='{$values['group_id']}'");
        $access=$sql->fetch_row($qry_data);
        $i=0;
        $qry_header=$sql->query("DESCRIBE groups");
        while($header=$sql->fetch_array($qry_header))
        {
            $this->access[$header['Field']]=$access[$i];
            $i++;
        }
	}

	private function updateCookie($cookie, $save)
	{
		$_SESSION['cookie'] = $cookie;
		if ($save)
		{
			$cookie = serialize(array($_SESSION['user'], $cookie));
			setcookie('logincookie', $cookie, time() + 31104000, '', '');
		}
	}

	private function checkRemembered($cookie)
	{
        global $sql;
		list($username, $cookie) = unserialize($cookie);
		if (!$username || !$cookie) return;
		$username = val_string($username);
		$cookie = val_string($cookie);

		$sqlq = "SELECT * FROM `employees` WHERE `user` = '$username' AND `cookie` = '$cookie'";
		$result = $sql->query( $sqlq );
		if ($sql->num_rows())
		{
			$this->setSession($sql->fetch_array($result), true );
		}
	}

	private function checkSession()
	{
        global $sql;
		$username = $_SESSION['user'];
		$cookie = $_SESSION['cookie'];
		$session = session_id();
		$ip = $_SERVER['REMOTE_ADDR'];
		$sqlq = "SELECT * FROM `employees` WHERE `user` = '$username' AND `cookie` = '$cookie' AND `session` = '$session' AND `ip` = '$ip'";
        $result = $sql->query($sqlq);
		if ($sql->num_rows())
		{
			$this->setSession($sql->fetch_array($result), false, false);
		}
		else
		{
			$this->logout();
		}
	}
    
    public function logged()
    {
		if (isset($_SESSION['logged']) && $_SESSION['logged'] == true && $_SESSION['user']!='')
		{
			return true;
		}
		return false;
    }

	public function logout()
	{
		$_SESSION['user'] = '';
		$_SESSION['IP'] = $_SERVER['REMOTE_ADDR'];
        $_SESSION['logged'] = false;
        unset($_SESSION);
        setcookie('logincookie', '', 0, '', '');
        if(isset($_SESSION['user']))
        {
            return false;
        }
        return true;
	}
    public function debug()
    {
        print_r($_SESSION);
        echo '<br />';
        print_r($this->access);
    }
    public function encpass($password)
    {
        global $sql;
        return md5($sql->escape($password));
    }
    
    public function reguser($acc, $pass, $ref)
    {
        global $sql;

        $acc = $sql->escape($acc);
        $pass0=$sql->escape($pass);
        $pass = $this->encpass($pass);
        $ip = $sql->escape($_SERVER['REMOTE_ADDR']);

   	    $sql->query("INSERT INTO `employees` (`user`, `pass`, `group_id`, `lastIP`) VALUES ('".$acc."', '".$pass."', '0', '$ip')");
        if($this->checkLogin($acc,$pass0, 0))
            return true;
        else
            return false;
    }
    
    public function changepass($acc,$old,$pass,$pass2)
    {
        global $sql, $Lang;
        
        if(ereg("^([a-zA-Z0-9_-])*$", $old) && ereg("^([a-zA-Z0-9_-])*$", $pass) && ereg("^([a-zA-Z0-9_-])*$", $pass2))
        {
            if ($pass==$pass2)
            {
                $result=$sql->query("SELECT `user`, `pass` FROM `employees` WHERE `user`='$acc' AND `pass`='".$this->encpass($old));
                if ($sql->num_rows())
                {
                    $sql->query("UPDATE `employees` SET `pass`='".$this->encpass($pass)."' WHERE `user`='{$acc}'");
                    suc('Success',$Lang['password_changed']);
                }
                else
                {
                    err('Error',$Lang['old_password_incorret']);
                }
            }
            else
            {
                err('Error',$Lang['passwords_no_match']);
            }
        }
        else
        {
	       err('Error',$Lang['incorrect_chars']);
        }
    }
    public function hasAccess($s)
    {
        if($s==null || $s=='') return 1;
        else if(isset($this->access[$s]))
            return $this->access[$s];
        else
            return $this->createAccess($s);
    }
    public function getGroupName()
    {
        return $$this->array['name'];
    }
    public function getGroupId()
    {
        return $$this->array['id'];
    }
    public function createAccess($s)
    {
        global $sql;
        $s=$sql->escape($s);
        $this->access[$s]=0;
        
        $sql->query("ALTER TABLE `groups` ADD COLUMN `$s`  tinyint(1) UNSIGNED NOT NULL DEFAULT 0;");
        msg('Warning', 'Access '.$s.' not defined. Creating now with default 0 value for all groups!', 'warning');
        return 0;
    }
    public function getUser()
    {
        return isset($_SESSION['user'])?$_SESSION['user']:null;
    }
    public function getColor()
    {
        return "#000000";
    }
    public function setVar($var,$val)
    {
        global $sql;
        switch($var)
        {
            case 'lang':
            case 'skin':
            case 'lastAccess':
                $_SESSION[$var]=$val;
                $sql->query("UPDATE employees SET `$var`='$val' WHERE user='".$this->getUser()."';");
            break;
            default:
                ($val=='no' || $val=='false'||$val=='n'||$val=='f'||$val=='0')?$val=0:$val=1;
                if(isset($_SESSION[$var]))
                {
                    $_SESSION[$var]=$val;
                    $sql->query("UPDATE employees SET `$var`='$val' WHERE user='".$this->getUser()."';");
                }
                else
                {
                    $this->createVar($var);
                    $this->setVar($var,$val);
                }
            break;
            
        }
    }
    public function getVar($var)
    {
        if(isset($_SESSION[$var]))
        {
            return $_SESSION[$var];
        }
        else
        {
            $this->createVar($var);
            return $this->getVar($var);
        }
    }
    private function createVar($var)
    {
        global $sql;
        $sql->query("ALTER TABLE employees ADD COLUMN `$var` tinyint(1) NOT NULL DEFAULT 0;");
        $_SESSION[$var]=0;
    }
}
?>